<template>
  <view class="clubmember-container">
    <!-- 页面标题 -->
    <view class="header">
      <view class="title">会员管理</view>
      <view class="subtitle">管理家族会员信息</view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-section">
      <view class="search-bar">
        <wd-search
          v-model="searchKeyword"
          placeholder="搜索会员姓名"
          :maxlength="20"
          hide-cancel
          @search="handleSearch"
          @clear="handleClear"
        />
      </view>
    </view>

    <!-- 会员列表 -->
    <view class="member-list">
      <view v-if="loading && memberList.length === 0" class="loading-container">
        <wd-loading size="large" />
        <text class="loading-text">加载中...</text>
      </view>

      <view v-else-if="!loading && memberList.length === 0" class="empty-container">
        <wd-icon name="user" size="60px" color="#ccc" />
        <text class="empty-text">暂无会员数据</text>
      </view>

      <scroll-view
        v-else
        scroll-y
        class="member-scroll"
        refresher-enabled
        :refresher-triggered="refreshing"
        @scrolltolower="loadMore"
        @refresherrefresh="handleRefresh"
      >
        <view v-for="member in memberList" :key="member.id" class="member-item">
          <view class="member-info">
            <view class="member-avatar">
              <!-- <wd-avatar :src="member.avatar || defaultAvatarUrlMen" size="large" /> -->
              <!-- <view :class="['status-badge', member.status]">{{ getStatusText(member.status) }}</view> -->
            </view>
            <view>
              <view class="member-name">{{ member.username || "未填写姓名" }}</view>
              <view class="member-phone">{{ member.mobile || "未填写手机号" }}</view>
              <view class="member-time">加入时间：{{ formatDate(member.createTime) }}</view>
              <view class="member-id">
                会员ID：{{ member.id }}
                <wd-icon
                  v-if="member.gender == 1"
                  size="14px"
                  name="gender-male"
                  class="color-#4D80F0"
                />
                <wd-icon
                  v-else-if="member.gender == 2"
                  size="14px"
                  name="gender-female"
                  class="color-#FA4350"
                />
              </view>
            </view>
          </view>

          <view class="member-status">
            <wd-tag
              class="status-tag"
              :type="member.memberLevelId == '16' ? 'danger' : 'primary'"
              mark
              plain
            >
              {{ member.levelName }}
            </wd-tag>
            <wd-button style="float: right" type="info" @click="handleConcat(member)">
              查看关联
            </wd-button>
          </view>
        </view>
        <view v-if="hasMore" class="load-more">
          <wd-loading size="small" />
          <text>加载更多...</text>
        </view>
        <view v-else-if="memberList.length > 0" class="no-more">
          <text>没有更多了</text>
        </view>
      </scroll-view>
    </view>
  </view>
  <!-- 查看关联 -->
  <wd-popup
    v-model="concatFlag"
    :closable="true"
    position="bottom"
    custom-style="border-radius:32rpx 32rpx 0 0;"
    @close="handleClose"
  >
    <Clubmember />
  </wd-popup>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import FamilyUserAPI from "@/api/genealogy/family-user";
import Clubmember from "@/pages/mine/clubmember/components/index.vue";

const defaultAvatarUrlMen = ref("https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/e73f70149e504ceca250fb288ca891b4.png");
const concatFlag = ref(false);

// 响应式数据
const searchKeyword = ref("");
const loading = ref(false);
const hasMore = ref(true);
const pageNum = ref(1);
const pageSize = 10;
const refreshing = ref(false);
const total = ref(0);

const memberList = ref<any[]>([]);

//
const handleConcat = (member: any) => {
  console.log(member);
  concatFlag.value = true;
};
const handleClose = () => {
  concatFlag.value = false;
};

// 方法定义
const loadMembers = (loadMore = false) => {
  if (!loadMore && !refreshing.value) {
    loading.value = true;
  }
  const queryParams = {
    pageNum: pageNum.value,
    pageSize: pageSize,
    ...(searchKeyword.value && { name: searchKeyword.value }),
  };

  FamilyUserAPI.getMembersPage(queryParams)
    .then((res: any) => {
      const processedList = res.list.map((item: any) => ({
        ...item,
        id: item.id || item.userId,
        username: item.username || item.name || "未填写姓名",
        mobile: item.mobile || item.phone || "未填写手机号",
        createTime: item.createTime || item.joinTime,
        avatar: item.avatar || item.headImg || defaultAvatarUrlMen.value,
      }));

      if (loadMore) {
        memberList.value.push(...processedList);
      } else {
        memberList.value = processedList;
      }

      // 更新总记录数
      total.value = res.total || 0;
      // 判断是否还有更多数据
      hasMore.value = memberList.value.length < total.value;
    })
    .finally(() => {
      loading.value = false;
    });
};

const loadMore = () => {
  if (!hasMore.value || loading.value || refreshing.value) return;

  pageNum.value++;
  loadMembers(true);
};

const handleSearch = () => {
  pageNum.value = 1;
  hasMore.value = true;
  loadMembers();
};

const handleClear = () => {
  searchKeyword.value = "";
  pageNum.value = 1;
  hasMore.value = true;
  loadMembers();
};

const formatDate = (dateStr: string) => {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
};

const handleRefresh = async () => {
  refreshing.value = true;
  pageNum.value = 1;
  hasMore.value = true;
  // 清空列表避免闪烁
  memberList.value = [];
  try {
    await loadMembers();
  } finally {
    refreshing.value = false;
  }
};

// 生命周期
onMounted(() => {
  loadMembers();
});
</script>

<style lang="scss" scoped>
.clubmember-container {
  max-height: 94vh;
  background-color: #f5f5f5;
}

.header {
  padding: 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;

  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }

  .subtitle {
    font-size: 24rpx;
    color: #666;
    margin-top: 8rpx;
  }
}

.search-section {
  padding: 20rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.member-list {
  flex: 1;

  .loading-container,
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;

    .loading-text,
    .empty-text {
      margin-top: 20rpx;
      font-size: 28rpx;
      color: #666;
    }
  }

  .member-scroll {
    height: calc(100vh - 400rpx);
  }

  .member-item {
    display: flex;
    align-items: center;
    padding: 30rpx;
    background-color: #fff;
    margin: 0 20rpx 20rpx;
    border-radius: 12rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

    .member-avatar {
      position: relative;
      margin-right: 20rpx;

      .status-badge {
        position: absolute;
        top: -8rpx;
        right: -8rpx;
        padding: 4rpx 8rpx;
        border-radius: 12rpx;
        font-size: 20rpx;
        color: #fff;

        &.active {
          background-color: #52c41a;
        }

        &.pending {
          background-color: #faad14;
        }

        &.inactive {
          background-color: #ff4d4f;
        }
      }
    }

    .member-info {
      flex: 1;

      .member-name {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 8rpx;
      }

      .member-phone {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 4rpx;
      }

      .member-time {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 4rpx;
      }

      .member-id {
        font-size: 22rpx;
        color: #ccc;

        .gender-tag {
          margin-left: 10rpx;
          padding: 2rpx 8rpx;
          border-radius: 4rpx;
          font-size: 20rpx;
          font-weight: bold;

          &.male {
            background-color: #e6f7ff;
            color: #1890ff;
          }

          &.female {
            background-color: #fff0f6;
            color: #eb2f96;
          }
        }
      }
    }

    .member-status {
      font-size: 24rpx;
      padding: 4rpx 12rpx;
      border-radius: 12rpx;
      width: 8rem;
      .status-tag {
        float: right;
        margin-bottom: 0.6rem;
      }
      &.status-active {
        color: #52c41a;
        background-color: #f6ffed;
      }

      &.status-pending {
        color: #faad14;
        background-color: #fff7e6;
      }

      &.status-inactive {
        color: #ff4d4f;
        background-color: #fff2f0;
      }
    }
  }

  .load-more,
  .no-more {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 30rpx;
    font-size: 24rpx;
    color: #999;
  }
}
</style>
